import fs from 'fs';
import path from 'path';
import chalk from 'chalk';
import pkg from '../package.json';
import { getDirname } from './utils';

async function core() {
  const __dirname = getDirname(import.meta.url);
  // 生成.env文件
  const envPath = path.join(__dirname, '..', '.env');
  const { PLATFORM = 'pc', DARK_MODE, ENV = 'dev' } = process.env;
  let platform = PLATFORM;
  if (isMobile(platform)) platform = 'mobile';
  const fileName = `.env.${platform}`;
  const content = fs.readFileSync(path.join(__dirname, '..', fileName), 'utf-8');
  const internalContent = [
    'SM_MAPBOX_TOKEN=pk.eyJ1IjoiZXhhbXBsZXMiLCJhIjoiY2p0MG01MXRqMW45cjQzb2R6b2ptc3J4MSJ9.zA2W0IkI0c6KaAhJfk9bWg',
    'SM_GEOVIS_TOKEN=62d17dd1bcd9b6b4cde180133d80aa420446c9d132f88cb84c29d51e77d01c4c',
    'SM_TIANDITU_TOKEN=211138deb6faa1f236b45eacd0fd331d',
    `SM_APP_VERSION=${pkg.version}`,
    `SM_WEBAPP_ENV=${ENV}`,
  ];

  fs.writeFileSync(envPath, `${content}\n${internalContent.join('\n')}`, 'utf-8');

  // 生成index.html
  let template = fs.readFileSync(path.resolve(__dirname, 'templates/index.html'), { encoding: 'utf-8' });
  let src = '';
  if (!template) return;
  if (platform === 'windows') {
    src = `/src/platform/windows/main.tsx`;
  } else if (isMobile(platform)) {
    src = `/src/platform/mobile/main.tsx`;
  } else {
    src = `/src/platform/pc/main.tsx`;
  }

  // 主题
  template = template.replace(
    'theme-mode="{theme}"',
    DARK_MODE && (platform === 'windows' || platform === 'pc') ? 'theme-mode="dark"' : '',
  );
  // 平台
  template = template.replace('src="{src}"', `src="${src}"`);
  fs.writeFileSync(path.resolve(__dirname, '..', 'index.html'), template);

  // 生成config.json
  const publicDirname = path.join(__dirname, '..', 'public');
  const distConfigDirname = path.join(publicDirname, 'config');
  if (!fs.existsSync(distConfigDirname)) fs.mkdirSync(distConfigDirname, { recursive: true });
  const config = await import(`../src/config/config.${ENV}`);
  fs.writeFileSync(path.join(distConfigDirname, 'config.json'), JSON.stringify(config.default, null, 2));
  console.log(chalk.bgGreen(`[prepare] ${platform}环境准备完成，入口文件为${src}`));
}

function isMobile(platform: string) {
  return /android|ios|mobile/.exec(platform);
}
core();
